package com.viknix.threadpool.manager.client.consistency;

import com.viknix.threadpool.manager.client.constant.Constants;
import com.viknix.threadpool.manager.client.exception.TpmProcessException;
import com.viknix.threadpool.manager.client.filter.ConfigFilterChainManager;
import com.viknix.threadpool.manager.client.filter.ConfigResponse;
import com.viknix.threadpool.manager.client.global.GlobalThreadPoolManage;
import com.viknix.threadpool.manager.client.listener.AbstractSharedListener;
import com.viknix.threadpool.manager.client.listener.Listener;
import com.viknix.threadpool.manager.client.listener.ManagerListenerWrap;
import com.viknix.threadpool.manager.client.util.MD5;
import com.viknix.threadpool.manager.common.util.ContentUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: Dongqi
 * @Date: 2021/10/24 18:04
 * @Version 1.0
 * @Description: 一个线程池对应一个CacheData
 */
@Data
@Slf4j
public class CacheData {

    private final String name;
    private final ConfigFilterChainManager configFilterChainManager;
    public final String poolId;
    public final String item;

    /**
     * 实际上就是 namespace
     */
    public final String namespace;

    /**
     * 用于存放 Listener
     */
    private final CopyOnWriteArrayList<ManagerListenerWrap> listeners;

    private volatile String md5;
    /**
     * whether use local config
     */
    private volatile boolean isUseLocalConfig = false;
    /**
     * last modify time
     */
    private volatile long localConfigLastModified;
    private volatile String content;
    private int taskId;
    private volatile boolean isInitializing = true;

    public boolean isInitializing() {
        return isInitializing;
    }

    public void setInitializing(boolean isInitializing) {
        this.isInitializing = isInitializing;
    }

    public String getMd5() {
        return md5;
    }

    public String getNamespace() {
        return namespace;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String newContent) {
        this.content = newContent;
        this.md5 = getMd5String(content);
    }

    /**
     * Add listener
     * if CacheData already set new content, Listener should init lastCallMd5 by CacheData.md5
     *
     * @param listener listener
     */
    public void addListener(Listener listener) {
        if (null == listener) {
            throw new IllegalArgumentException("listener is null");
        }
        ManagerListenerWrap wrap = new ManagerListenerWrap(listener, md5);
        if (listeners.addIfAbsent(wrap)) {
            log.info("[{}] [add-listener] ok, namespace={}, poolId={}, item={}, cnt={}", name, namespace, poolId, item,
                    listeners.size());
        }
    }

    public void removeListener(Listener listener) {
        if (null == listener) {
            throw new IllegalArgumentException("listener is null");
        }
        ManagerListenerWrap wrap = new ManagerListenerWrap(listener);
        if (listeners.remove(wrap)) {
            log.info("[{}] [remove-listener] ok, poolId={}, item={}, cnt={}", name, poolId, item, listeners.size());
        }
    }

    /**
     * 返回监听器列表上的迭代器，只读。保证不返回NULL。
     */
    public List<Listener> getListeners() {
        List<Listener> result = new ArrayList<Listener>();
        for (ManagerListenerWrap wrap : listeners) {
            result.add(wrap.listener);
        }
        return result;
    }

    public long getLocalConfigInfoVersion() {
        return localConfigLastModified;
    }

    public void setLocalConfigInfoVersion(long localConfigLastModified) {
        this.localConfigLastModified = localConfigLastModified;
    }

    public boolean isUseLocalConfigInfo() {
        return isUseLocalConfig;
    }

    public void setUseLocalConfigInfo(boolean useLocalConfigInfo) {
        this.isUseLocalConfig = useLocalConfigInfo;
        if (!useLocalConfigInfo) {
            localConfigLastModified = -1;
        }
    }

    public int getTaskId() {
        return taskId;
    }

    public void setTaskId(int taskId) {
        this.taskId = taskId;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((poolId == null) ? 0 : poolId.hashCode());
        result = prime * result + ((item == null) ? 0 : item.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (null == obj || obj.getClass() != getClass()) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        CacheData other = (CacheData) obj;
        return poolId.equals(other.poolId) && item.equals(other.item);
    }

    @Override
    public String toString() {
        return "CacheData [" + poolId + ", " + item + "]";
    }

    public void checkListenerMd5() {
        for (ManagerListenerWrap wrap : listeners) {
            if (!md5.equals(wrap.lastCallMd5)) {
                safeNotifyListener(poolId, item, content, md5, wrap);
            }
        }
    }

    private void safeNotifyListener(final String poolId, final String item, final String content,
                                    final String md5, final ManagerListenerWrap listenerWrap) {
        final Listener listener = listenerWrap.listener;

        Runnable job = new Runnable() {
            @Override
            public void run() {
                ClassLoader myClassLoader = Thread.currentThread().getContextClassLoader();
                ClassLoader appClassLoader = listener.getClass().getClassLoader();
                try {
                    if (listener instanceof AbstractSharedListener) {
                        AbstractSharedListener adapter = (AbstractSharedListener) listener;
                        adapter.fillContext(poolId, item);
                        log.info("[{}] [notify-context] poolId={}, item={}, md5={}", name, poolId, item, md5);
                    }
                    // 执行回调之前先将线程classloader设置为具体webapp的classloader，以免回调方法中调用spi接口是出现异常或错用（多应用部署才会有该问题）。
                    Thread.currentThread().setContextClassLoader(appClassLoader);

                    ConfigResponse cr = new ConfigResponse();
                    cr.setPoolId(poolId);
                    cr.setItem(item);
                    cr.setContent(content);
                    configFilterChainManager.doFilter(null, cr);
                    String contentTmp = cr.getContent();
                    // 回调监听函数
                    listener.receiveConfigInfo(contentTmp);
                    listenerWrap.lastCallMd5 = md5;
                    log.info("[{}] [notify-ok] poolId={}, item={}, md5={}, listener={} ", name, poolId, item, md5,
                            listener);
                } catch (TpmProcessException de) {
                    log.error("[{}] [notify-error] poolId={}, item={}, md5={}, listener={} errCode={} errMsg={}", name,
                            poolId, item, md5, listener, de.getErrCode(), de.getErrMsg());
                } catch (Throwable t) {
                    log.error("[{}] [notify-error] poolId={}, item={}, md5={}, listener={} tx={}", name, poolId, item,
                            md5, listener, t.getCause());
                } finally {
                    Thread.currentThread().setContextClassLoader(myClassLoader);
                }
            }
        };

        final long startNotify = System.currentTimeMillis();
        try {
            if (null != listener.getExecutor()) {
                listener.getExecutor().execute(job);
            } else {
                job.run();
            }
        } catch (Throwable t) {
            log.error("[{}] [notify-error] poolId={}, item={}, md5={}, listener={} throwable={}", name, poolId, item,
                    md5, listener, t.getCause());
        }
        final long finishNotify = System.currentTimeMillis();
        log.info("[{}] [notify-listener] time cost={}ms in ClientWorker, poolId={}, item={}, md5={}, listener={} ",
                name, (finishNotify - startNotify), poolId, item, md5, listener);
    }

    static public String getMd5String(String config) {
        return (null == config) ? Constants.NULL : MD5.getInstance().getMD5String(config);
    }

    public CacheData(ConfigFilterChainManager configFilterChainManager, String name, String poolId, String item, String namespace) {
        if (null == poolId || null == item) {
            throw new IllegalArgumentException("poolId=" + poolId + ", item=" + item);
        }
        this.name = name;
        this.configFilterChainManager = configFilterChainManager;
        this.poolId = poolId;
        this.item = item;
        this.namespace = namespace;
        listeners = new CopyOnWriteArrayList<ManagerListenerWrap>();
        this.isInitializing = true;
        this.content = loadCacheContentFromCache(poolId);
        this.md5 = getMd5String(content);
    }

    private String loadCacheContentFromCache(String poolId) {
        return ContentUtil.getPoolContent(GlobalThreadPoolManage.getPoolParameter(poolId));
    }
}
